<?php

namespace app\api\controller\shop;


use app\common\controller\Api;
use app\common\model\goods\Apply;
use app\common\model\goods\Applyinfo;
use app\common\model\Shop;
use app\common\model\shop\Cart;
use app\common\model\shop\Goods as GoodsModel;
use app\common\model\shop\goods\User;
use fast\Random;
use think\Validate;

/**
 * 商品
 * @ApiWeigh (96)
 */
class Goods extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['reclist'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // protected $auth = ['test3'];


    /**
     * 商品列表
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="category_id", type="int", required=false, description="分类ID 不传为全部商品")
     * @ApiParams (name="custom_id", type="int", required=false, description="客户ID")
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':'0','msg':'返回成功'})
     */
    public function list()
    {
        // $rej = $this->validate(
        //     $this->request->post(),
        //     [
        //         'category_id'  => 'require|number|egt:1',
        //     ]
        // );
        // if (true !== $rej) {
        //     $this->responseMsg(1005, [], $rej);
        // }
        $keywords = $this->request->post('keywords');
        $pid = $this->request->post('pid');
        $category_id = $this->request->post('category_id');

        $model = new GoodsModel;
        $model->alias('g');
        if (isset($keywords) && $keywords) {
            $model->whereLike('title', '%' . $keywords . '%');
        }
        $user = $this->auth->getUser();

        if ($this->request->post('custom_id')) {
            if (isset($category_id) && $category_id) {
                $model->where('g.category_id', $this->request->post('category_id'));
            }
            if (isset($pid) && $pid) {
                $model->where('g.first_cate', $pid);
            }
            $model->where('g.custom', 0);
            $res = $model
                ->where('g.sale_switch', 1)
                ->join('shop_cart c', "g.id=c.goods_id and c.user_id={$user->id} and custom_id = {$this->request->post('custom_id')}", 'left')
                ->order('g.weigh desc,g.id desc')
                ->field('g.*,ifnull(c.total,0) as num')
                ->paginate();
        } else {
            if (isset($category_id) && $category_id) {
                $model->where('category_id', $this->request->post('category_id'));
            }
            if (isset($pid) && $pid) {
                $model->where('first_cate', $pid);
            }
            $model->where('custom', 0);
            $res = $model->where('sale_switch', 1)
                ->order('weigh desc,id desc')
                // ->field('*,0 as num')
                ->paginate();
        }

        // $res = api_format_img($res,'thumb_image');
        // $res = mutrl_format_img($res,'images');

        $this->responseMsg(0, $res);
    }

    /**
     * @Author LK
     * @date: 2024-10-08
     * @ApiTitle (定制商品申请)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="编辑ID")
     * @ApiParams (name="name", type="integer", required=true, sample="", description="产品名称")
     * @ApiParams (name="spec", type="integer", required=true, sample="", description="产品规格")
     * @ApiParams (name="tags", type="integer", required=true, sample="", description="标签")
     * @ApiParams (name="price", type="integer", required=true, sample="", description="价格")
     * @ApiParams (name="images", type="integer", required=true, sample="", description="授权证书")
     * @ApiParams (name="trademark", type="integer", required=true, sample="", description="商标")
     * @ApiParams (name="store", type="integer", required=true, sample="", description="门店")
     * @ApiParams (name="demand", type="integer", required=true, sample="", description="月需求量")
     * @ApiParams (name="content", type="integer", required=true, sample="", description="其他")
     * @ApiParams (name="apply_user", type="integer", required=true, sample="", description="申请人姓名")
     * @ApiParams (name="mobile", type="integer", required=true, sample="", description="申请人电话")
     * @ApiParams (name="is_back", type="integer", required=true, sample="", description="是否寄回")
     * @ApiParams (name="back_name", type="integer", required=true, sample="", description="寄回人")
     * @ApiParams (name="back_mobile", type="integer", required=true, sample="", description="寄回电话")
     * @ApiParams (name="back_address", type="integer", required=true, sample="", description="寄回地址")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function custom_apply()
    {
        $params = request()->param();
        extract($params);
        $validate = new Validate([
            ['name', 'require', '产品名称不能为空'],
            ['spec', 'require', '产品规格不能为空'],
            ['tags', 'require', '产品标签不能为空'],
            ['price', 'require', '产品价格不能为空'],
            ['images', 'require', '授权证书不能为空'],
            ['trademark', 'require', '商标信息不能为空'],
            ['store', 'require', '门店信息不能为空'],
            ['demand', 'require', '月需求量不能为空'],
            ['apply_user', 'require', '申请人姓名不能为空'],
            ['mobile', 'require', '申请人电话不能为空'],
        ]);
        if (!$validate->check($params)) {
            $this->responseMsg(1005, [], $validate->getError());
        };
        $monthly_demand = config('site.monthly_demand') ?? 0;
        if ($demand < $monthly_demand) {
            $this->responseMsg(1005, [], '月需求量必须大于' . $monthly_demand);
        }
        $apply = Apply::get($id);
        if ($apply) {
            $res = $apply->isUpdate(true)->save($params);
        } else {
            $params['user_id'] = $this->auth->id;
            $params['sn'] = sn('apply_goods', 'sn');
            $res = Apply::create($params);
        }
        if ($res) {
            $this->responseMsg(0, [], '操作成功');
        }
        $this->responseMsg(1, [], '操作失败');
    }
    /**
     * @Author LK
     * @date: 2024-10-08
     * @ApiTitle (删除申请)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function del_apply()
    {
        $params = request()->param();
        extract($params);
        $validate = new Validate([
            ['id', 'require', '参数错误'],
        ]);
        if (!$validate->check($params)) {
            $this->responseMsg(1005, [], $validate->getError());
        };
        $apply = Apply::get($id);
        $apply->delete();
        $this->responseMsg(0, [], '删除成功');
    }

    /**
     * @Author LK
     * @date: 2024-10-08
     * @ApiTitle (申请列表)
     * @ApiMethod (GET)
     * @ApiParams (name="status", type="integer", required=true, sample="", description="状态:0=待审核,1=已通过,2=未通过")
     * @ApiParams (name="page", type="integer", required=true, sample="", description="页码")
     * @ApiParams (name="limit", type="integer", required=true, sample="", description="每页数量")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function apply_list()
    {
        $params = request()->param();
        extract($params);
        $model = new Apply();
        if (isset($status)) {
            $model->where('status', $status);
        }
        $list = $model->where('user_id', $this->auth->id)->order('id desc')->paginate($limit ?? 10);
        $this->responseMsg(0, $list);
    }
    /**
     * @Author LK
     * @date: 2024-10-08
     * @ApiTitle (申请详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function apply_info()
    {
        $params = request()->param();
        extract($params);
        if (!isset($id) || !$id) {
            $this->responseMsg(1, [], '参数错误');
        }
        $info =  Apply::get($id);
        $this->responseMsg(0, $info);
    }
    /**
     * 定制商品列表
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="custom_id", type="int", required=false, description="客户ID")
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':'0','msg':'返回成功'})
     */
    public function custom_list()
    {


        $rej = $this->validate(
            $this->request->post(),
            [
                'custom_id'  => 'require|number|egt:1',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $params = request()->param();
        extract($params);
        $uid = $this->auth->id;
        $goods_ids = User::where('user_id', $uid)->column('goods_id');
        $model = new GoodsModel;
        $model->alias('g');
        $model->whereIn('g.id', $goods_ids);
        $model->where('custom', 1);
        if (isset($keywords) && $keywords) {
            $model->whereLike('title', '%' . $keywords . '%');
        }
        $user = $this->auth->getUser();
        $res = $model
            ->where('g.sale_switch', 1)
            // ->where('find_in_set(:id,acct_ids)', ['id' => $this->auth->acct_id])
            ->join('shop_cart c', "g.id=c.goods_id and c.user_id={$user->id} and custom_id = {$this->request->post('custom_id')}", 'left')
            ->order('g.weigh desc,g.id desc')
            ->field('g.*,ifnull(c.total,0) as num')
            ->paginate();
        $this->responseMsg(0, $res);
    }


    /**
     * 商品详情
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, description="商品id")
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function detail()
    {

        $rej = $this->validate(
            $this->request->post(),
            [
                'id'  => 'require|number',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $res = GoodsModel::where('id', $this->request->post('id'))->find();
        if (!$res) {
            $this->responseMsg(1007, '', '没有找到数据');
        }
        $this->responseMsg(0, $res->toArray());
    }

    /**
     * @Author LK
     * @date: 2024-10-28 16:14:43
     * @ApiTitle (定制商品进程)
     * @ApiMethod (GET)
     * @ApiParams (name="apply_id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    function process()
    {
        $params = request()->param();
        extract($params);
        $validate = new Validate([
            ['apply_id', 'require', '参数错误'],
        ]);
        if (!$validate->check($params)) {
            $this->responseMsg(1005, [], $validate->getError());
        }
        $list = Applyinfo::where('apply_id', $apply_id)->order('id desc')->select();
        foreach ($list as $key => $v) {
            $v->idx = count($list) - $key;
        }
        $this->responseMsg(0, $list);
    }

    /**
     * @Author LK
     * @date: 2025-01-15 15:02:30
     * @ApiTitle (报价单)
     * @ApiMethod (POST)
     * @ApiParams (name=goods_info, type='array', required=true, sample='', description='')
     * @ApiReturnParams (name='code', type='integer', required=true, description='')
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function quotation()
    {
        $params = request()->param();
        extract($params);
        $validate = new Validate([
            'goods_info' => 'require',
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        $array = [];
        $total_price = 0;
        foreach ($goods_info as $k => $v) {
            $goods = GoodsModel::where('id', $v['id'])->field('id,title,intro,unit,brand')->find();
            $goods['num'] = $v['num'];
            $goods['pay_money'] = $v['pay_money'];
            $goods['subtotals'] = bcmul($v['pay_money'], $v['num'], 2);
            $total_price = bcadd($total_price, $goods['subtotals'], 2);
            array_push($array, $goods);
        }
        $this->success('请求成功', ['lists' => $array, 'sn' => 'SO' . Random::numeric(6), 'total_price' => $total_price]);
    }
}
